package com.hbsoft.wechat.service;

import com.hb.util.HttpUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.util.GsonUtil;
import com.hbsoft.wechat.bean.Area;
import com.hbsoft.wechat.bean.BattleInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GetBattleService {

    private final Logger logger = LoggerFactory.getLogger(getClass());


    public BattleInfo getBattleInfo(){
        BattleInfo battleInfo = (BattleInfo) Constant.battleMap.get("battleInfo");
        if (battleInfo == null) {
            battleInfo = getBattleInfoTime();
        }
        return battleInfo;
    }

    public BattleInfo getBattleInfoTime(){
        logger.info("定时获取疫情数据开始");
        String result = HttpUtil.sendGet("https://tianqiapi.com/api?version=epidemic&appid=13431&appsecret=1343431");
        BattleInfo battleInfo = GsonUtil.fromJson(result,BattleInfo.class);
        if("0".equals(battleInfo.getErrcode())){
            List<Area> areaList = battleInfo.getData().getArea();
            List<Area> sxAreaList = new ArrayList<>();
            for(Area area : areaList){
                if(area.getProvinceName().equals("山西")){
                    sxAreaList.add(area);
                    break;
                }
            }
            battleInfo.getData().setArea(sxAreaList);
        }
        Constant.battleMap.put("battleInfo",battleInfo);
        logger.info("定时获取疫情数据结束：{}",GsonUtil.toJson(battleInfo));
        return battleInfo;
    }
}
